#coding:utf-8
'''
create on 2017-04-20
@author:sandy
'''


from pycommon import TBaseProtocol
import LoginFactory
import logging
import LoginParse

LOGIN_STATE_INIT               = 0
LOGIN_STATE_LOGINED            = 1
LOGIN_STATE_TO_CLOSE           = 2

class LoginSrv(TBaseProtocol.TBaseProtocol):

    def __init__(self, pid, addr):
        TBaseProtocol.TBaseProtocol.__init__(self)
        self.__id = pid
        self.__addr = addr
        self.__ip = addr.host.decode('utf-8')
        self.__sid = 0
        self.state = LOGIN_STATE_INIT 
        
    def getId(self):
        return self.__id
    
    def getSId(self):
        return self.__sid
    
    def getIp(self):
        return self.__ip

    def getState(self):
        return self.state
    
    def packetReceived(self, cmd, pkt):
        if self.state == LOGIN_STATE_TO_CLOSE:
            return
        logging.debug(u"LoginSrv cmd=%d", cmd)
        try:
            LoginParse.parse(self, cmd, pkt)
        except Exception:
            logging.exception(u"LoginParse.parse(), cmd=%d" % cmd)
        
    def sendPacket(self, pkt):
        if not self.isConnected():
            logging.warn(u"sendPacket() not connected")
            return
        TBaseProtocol.TBaseProtocol.sendPacket(self, pkt)
    
    def connectionMade(self):
        logging.debug(u"LoginSrv.connectionMade() ip=%s", self.__ip) 
        TBaseProtocol.TBaseProtocol.reset(self)
   
    def connectionLost(self, reason):
        logging.debug(u"LoginSrv.connectionLost %s", reason)
        self.state = LOGIN_STATE_TO_CLOSE     
        LoginFactory.instance.removeProtocol(self)
        
    def onLogin(self, sid):
        self.__sid = sid 
        self.state = LOGIN_STATE_LOGINED     

if __name__ == "__main__":
    pass